<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            style="min-width: 230px"
            v-model="listQuery.name"
            placeholder="输入客户编号/名称/助记码"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-container>
        <el-aside width="218px">
          <el-tree
            :data="categories"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            node-key="id"
          ></el-tree>
        </el-aside>
        <el-main>
          <el-table
            :data="datas"
            border
            v-loading="listLoading"
            fit
            highlight-current-row
            style="width: 100%"
            size="small"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column
              v-for="column in tableColumns"
              :key="column.key"
              :label="column.title"
              :prop="column.key"
              :align="column.align"
              :width="column.width ? column.width : ''"
            >
              <template slot-scope="scope">
                <div v-if="column.key == 'name'">
                  <el-link
                    :underline="false"
                    type="primary"
                    @click="handleEdit(scope)"
                    >{{ scope.row[column.key] }}</el-link
                  >
                </div>
                <div v-else>
                  {{ scope.row[column.key] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                ></el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getCustomerList"
          />
        </el-main>
      </el-container>
    </el-card>

    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="800px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="110px"
        label-position="right"
        style="padding: 0 20px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="code">
              <el-input
                type="string"
                v-model="form.code"
                placeholder="客户编号"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="客户名称"
                clearable
                size="small"
                @input="getHanzi2Pinyin"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户分类" prop="cate">
              <el-cascader
                ref="cate"
                v-model="selectedKeys"
                :options="cates"
                :props="props"
                @change="handleChange"
                clearable
                size="small"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="助记码" prop="help_code">
              <el-input
                v-model="form.help_code"
                placeholder="助记码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="linkman">
              <el-input
                type="string"
                v-model="form.linkman"
                placeholder="联系人"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="telephone">
              <el-input
                v-model="form.telephone"
                placeholder="电话"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                type="string"
                v-model="form.email"
                placeholder="邮箱"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传真" prop="fax">
              <el-input
                type="string"
                v-model="form.fax"
                placeholder="传真"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开户行" prop="bank">
              <el-input
                v-model="form.bank"
                placeholder="开户行"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账户" prop="account">
              <el-input
                v-model="form.account"
                placeholder="银行账户"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="税号" prop="tax_code">
              <el-input
                v-model="form.tax_code"
                placeholder="税号"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否是客户" prop="is_customer">
              <el-switch v-model="form.is_customer" disabled></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否是供应商" prop="is_supplier">
              <el-switch v-model="form.is_supplier"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动积分" prop="active_point">
              <el-input
                v-model="form.active_point"
                placeholder="活动积分"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员积分" prop="member_point">
              <el-input
                v-model="form.member_point"
                placeholder="会员积分"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="消费积分" prop="consume_point">
              <el-input
                v-model="form.consume_point"
                placeholder="消费积分"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="备注"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="地址"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(false)"
          >保存</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { getParentsPath } from "@/utils/index";
import { mapGetters } from "vuex";
import {
  getCustomers,
  addCustomer,
  updateCustomer,
  delCustomer,
  delCustomers,
  getCustSuppClasses,
  getCustSuppMaxCode,
  hanzi2pinyin,
} from "@/api/base";

const defaultForm = {
  id: null,
  code: "",
  name: "",
  cate: null,
  linkman: "",
  telephone: "",
  fax: "",
  email: null,
  bank: "",
  account: "",
  tax_code: "",
  help_code: null,
  is_customer: true,
  is_supplier: null,
  address: "",
  remark: "",
  user: null,
};

export default {
  name: "Customer",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        code: [
          {
            required: true,
            message: "请输入客户编号",
            trigger: "blur",
          },
        ],
        name: [
          {
            type: "string",
            required: true,
            message: "请输入客户名称",
            trigger: "blur",
          },
        ],
      },

      tableColumns: [
        
        {
          key: "name",
          title: "客户名称",
          width: "240",
        },
        {
          key: "help_code",
          title: "助记码",
          width: "100",
        },
        {
          key: "code",
          title: "客户编号",
          width: "100",
        },
        {
          key: "cate_name",
          title: "客户分类",
          width: "120",
        },
        {
          key: "address",
          title: "地址",
          width: "180",
        },
        {
          key: "linkman",
          title: "联系人",
          width: "100",
        },
        {
          key: "telephone",
          title: "联系电话",
          width: "120",
        },
        {
          key: "fax",
          title: "传真",
          width: "100",
        },
        {
          key: "vip_name",
          title: "会员",
          width: "100",
        },
        {
          key: "email",
          title: "邮箱",
          width: "140",
        },
        {
          key: "bank",
          title: "开户行",
          width: "120",
        },
        {
          key: "account",
          title: "银行账户",
        },
        {
          key: "tax_code",
          title: "税号",
          width: "100",
        },
        {
          key: "supplier_flag",
          title: "是否是供应商",
          width: "100",
          align: "center",
        },
        {
          key: "remark",
          title: "备注",
          width: "180",
        },
        {
          key: "user_name",
          title: "创建人",
        },
      ],

      title: "客户资料",
      dialogVisible: false,
      dialogType: "new",
      datas: [],
      categories: [],
      cates: [],

      selectedKeys: [],
      selections: [],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: "",
        parent_id: null,
        cate_id: null,
      },
      //cascader
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      //tree
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getCustomerClassList();
    this.getCustomerList();
    this.getCustomerCode();
  },
  methods: {
    getHanzi2Pinyin() {
      const params = {
        name: this.form.name,
      };
      hanzi2pinyin(params).then((res) => {
        this.form.help_code = res.help_code;
      });
    },
    getCustomerCode() {
      getCustSuppMaxCode().then((res) => {
        this.form.code = res.max_code;
      });
    },

    getCustomerClassList() {
      getCustSuppClasses().then((res) => {
        this.cates = res;
        this.categories.push({ id: -1, name: "客商分类", children: res });
      });
    },
    getCustomerList() {
      this.listLoading = true;
      getCustomers(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          this.$message.error("获取数据失败!" + error);
          this.listLoading = false;
        });
    },
    //树形点击
    handleNodeClick(data) {
      if (data.children) {
        // 父类
        this.listQuery.parent_id = data.id;
        this.listQuery.cate_id = null;
      } else {
        this.listQuery.parent_id = null;
        this.listQuery.cate_id = data.id;
      }

      this.handleFilter();
    },

    handleChange(value) {
      console.log(value);
      if (this.selectedKeys.length > 0) {
        this.form.cate = this.selectedKeys[this.selectedKeys.length - 1];
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getCustomerList();
    },
    // 增加f
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.getCustomerCode();

      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改运营商
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(this.form.cate, this.cates);
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCustomer(row.id);
          this.getCustomerList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message({
            type: "error",
            message: "删除失败!",
          });
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },
    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delCustomers(sel_ids);
          this.getCustomerList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";

        if (this.form.user == null) {
          this.form.user = this.uid;
        }

        let res = null;

        if (isEdit) {
          res = await updateCustomer(this.form);
        } else {
          res = await addCustomer(this.form);
        }

        this.getCustomerList();

        const { code, name, cate_name } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
          this.getCustomerCode();
          this.form.cate = this.selectedKeys[this.selectedKeys.length - 1];
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>客户编号: ${code}</div>
              <div>客户名称: ${name}</div>
              <div>客户分类: ${cate_name || "无"}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.el-aside {
  .el-tree {
    border: 1px solid #eee;
    padding: 10px;
  }
}
.el-cascader,
.el-select {
  width: 100%;
}
.el-link {
  font-size: 12px;
}
</style>